package com.ztman.service.work.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ztman.basic.exception.BizException;

/**
 * @author: wsd
 * @date: 2021/9/14 15:13
 */
public class ProcessState {
    private JSONArray jsonArray ;
    ProcessState(JSONArray jsonArray){
        this.jsonArray = jsonArray;
    }
    public JSONObject getNode(String currentState){
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if(jsonObject.getString("id").equals(currentState)){
                return jsonObject;
            }
        }
        return null;
    }
    public JSONArray getEdge(String stateId, String classify){
        JSONArray edges = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject edge = jsonArray.getJSONObject(i);
            if (edge.getString(classify).equals(stateId)) {
                edges.add(edge);
            }
        }
        //冒泡排序
        for (int i = 0; i < edges.size(); i++) {
            for (int j = 1; j < edges.size()-i; j++) {
                if(edges.getJSONObject(j).getInteger("sort")==null ||
                        edges.getJSONObject(j-1).getInteger("sort")== null){
                    throw new BizException("流程未定义顺序属性，请确认");
                }
                int leftJsonSort = edges.getJSONObject(j).getIntValue("sort");
                int rightJsonSort = edges.getJSONObject(j-1).getIntValue("sort");

                if (leftJsonSort < rightJsonSort) {
                    JSONObject temp = new JSONObject();
                    JSONObject temp2 = new JSONObject();
                    temp.putAll(edges.getJSONObject(j));
                    temp2.putAll(edges.getJSONObject(j - 1));
                    edges.getJSONObject(j).clear();
                    edges.getJSONObject(j).putAll(temp2);
                    edges.getJSONObject(j - 1).clear();
                    edges.getJSONObject(j - 1).putAll(temp);
                }
            }
        }
        return edges;
    }

}
